package com.vitas.coin.ui.act;

import android.os.Handler;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;

import com.blankj.utilcode.util.BarUtils;
import com.snap.base.util.BaseUtil;
import com.snap.common.main.BaseMVVMAct;
import com.snap.util.ToastUtilKt;
import com.snap.util.edge.EdgePaddingMarginKt;
import com.vitas.coin.R;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.data.event.FavorEvent;
import com.vitas.coin.databinding.ActivityPlayMusicBinding;
import com.vitas.coin.manager.LocalMusicManager;
import com.vitas.coin.manager.PlayManager;
import com.vitas.coin.resp.CollectDaoResp;
import com.vitas.coin.task.SilentTask;
import com.vitas.coin.task.TaskEngine;
import com.vitas.coin.ui.dialog.Add2ListDlg;
import com.vitas.coin.ui.dialog.BaseDialogFragment;
import com.vitas.coin.ui.dialog.ListDlg;
import com.vitas.coin.vm.PlayVm;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PlayAct extends BaseMVVMAct<ActivityPlayMusicBinding, PlayVm> {

    private ExoPlayer mPlayer;
    private Timer timer = null;
    private Handler h = new Handler();
    private boolean prepared;
    private int current;
    private ArrayList<ChildrenVoiceBean> list;
    ListDlg dlg = null;

    Player.Listener listener = new Player.Listener() {
        @Override
        public void onRenderedFirstFrame() {
            if (current < 0) {
                return;
            }
            prepared = true;
            ChildrenVoiceBean bean = list.get(current);
            binding.tvTitle.setText(bean.getName());
            binding.ivLove.setImageResource(bean.isCollect() ? R.drawable.ic_pm_love_2 : R.drawable.ic_pm_love);
            long max = mPlayer.getDuration();
            if (max < 0) {
                max = mPlayer.getTotalBufferedDuration();
            }
            binding.seekBar.setMax((int) (max / 1000));
            binding.tvTimeTotal.setText(LocalMusicManager.getInstance(PlayAct.this).duration(max / 1000));
        }

        @Override
        public void onIsPlayingChanged(boolean isPlaying) {
            if (isPlaying) {
                binding.ivPlay.setImageResource(R.drawable.ic_pm_pause);
                startTimer();
            } else {
                binding.ivPlay.setImageResource(R.drawable.ic_pm_play);
                stopTimer();
            }
        }

        @Override
        public void onPlaybackStateChanged(int playbackState) {
            if (playbackState == Player.STATE_READY) {
                onRenderedFirstFrame();
            }
            if (playbackState == Player.STATE_ENDED) {
                timer.cancel();
                binding.tvTimeCurrent.setText(LocalMusicManager.getInstance(PlayAct.this).duration(0));
                binding.seekBar.setProgress(0);
                binding.ivPlay.setImageResource(R.drawable.ic_pm_play);
            }
        }

        @Override
        public void onPlayerError(PlaybackException error) {
            //播放异常
            ToastUtilKt.toast("无法播放该音频");
        }

        @Override
        public void onMediaItemTransition(
                @Nullable MediaItem mediaItem, @Player.MediaItemTransitionReason int reason) {
            if (mediaItem != null && mediaItem.localConfiguration != null) {
                ChildrenVoiceBean metadata = (ChildrenVoiceBean) mediaItem.localConfiguration.tag;
                current = list.indexOf(metadata);
                onRenderedFirstFrame();
                if (dlg != null && current >= 0) {
                    dlg.updateNow(current);
                }
            }
        }
    };

    @NonNull
    @Override
    public PlayVm createVM() {
        return new PlayVm();
    }

    @Override
    public void doDataBind() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_play_music;
    }

    private void initPlayer() {
        //停用声道数量限制
        mPlayer = PlayManager.getInstance().getPlayer();
        mPlayer.setRepeatMode(Player.REPEAT_MODE_ALL);
        mPlayer.setShuffleModeEnabled(false);
        mPlayer.addListener(listener);
    }

    private void startTimer() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateCurrent();
            }
        }, 0, 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }

    private void updateCurrent() {
        h.post(() -> {
            long now = mPlayer.getCurrentPosition() / 1000;
            binding.seekBar.setProgress((int) now);
            binding.tvTimeCurrent.setText(LocalMusicManager.getInstance(PlayAct.this).duration(now));
        });
    }

    private void play(List<ChildrenVoiceBean> list, int index) {
        PlayManager.getInstance().play(list, index, 0);
    }

    @Override
    public void onCreate() {
        EdgePaddingMarginKt.paddingVerticalSystemWindowInsets(binding.getRoot());
        BarUtils.transparentStatusBar(this);
        BarUtils.setStatusBarLightMode(this, true);

        binding.ivBack.setOnClickListener(v -> finish());
        initPlayer();
        list = getIntent().getParcelableArrayListExtra("list");
        current = getIntent().getIntExtra("index", 0);
        play(list, current);
        binding.ivPlay.setOnClickListener(v -> {
            if (!prepared) {
                return;
            }
            if (mPlayer.getPlaybackState() == Player.STATE_ENDED) {
                prepared = false;
                play(list, 0);
            } else {
                if (mPlayer.isPlaying()) {
                    mPlayer.pause();
                } else {
                    mPlayer.play();
                }
            }
        });
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mPlayer.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mPlayer.seekTo(seekBar.getProgress() * 1000);
                mPlayer.play();
            }
        });
        binding.ivPlaylist.setOnClickListener(v -> {
            dlg = new ListDlg().setParam(list, current, new ListDlg.ChangeListener() {
                @Override
                public void onRemove(int index) {
                    mPlayer.removeMediaItem(index);
                    if (list.isEmpty()) {
                        binding.tvTitle.setText("--");
                        binding.tvTimeCurrent.setText("00:00");
                        binding.tvTimeTotal.setText("00:00");
                    }
                }

                @Override
                public void onPlayChange(int index) {
                    mPlayer.seekTo(index, 0);
                }
            });
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    dlg = null;
                }
            });
            dlg.show(getSupportFragmentManager(), "");
        });
        binding.ivNext.setOnClickListener(v -> {
            mPlayer.seekToNextMediaItem();
        });
        binding.ivPrevious.setOnClickListener(v -> {
            mPlayer.seekToPreviousMediaItem();
        });
        binding.ivType.setOnClickListener(v -> changePlayType());
        binding.ivLove.setOnClickListener(v -> {
            if (current < 0) {
                return;
            }
            collect(list.get(current));
        });
        binding.ivAdd.setOnClickListener(v -> {
            new Add2ListDlg().setChildData(list.get(current)).show(getSupportFragmentManager(), "");
        });
    }

    private void collect(ChildrenVoiceBean musicObj) {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                if (musicObj.isCollect()) {
                    musicObj.setCollect(false);
                    CollectDaoResp.INSTANCE.delete(musicObj);
                    h.post(() -> {
                        binding.ivLove.setImageResource(R.drawable.ic_pm_love);
                        BaseUtil.INSTANCE.postEvent(new FavorEvent(musicObj.getId(), false));
                    });
                } else {
                    musicObj.setCollect(true);
                    CollectDaoResp.INSTANCE.upsert(musicObj);
                    h.post(() -> {
                        binding.ivLove.setImageResource(R.drawable.ic_pm_love_2);
                        BaseUtil.INSTANCE.postEvent(new FavorEvent(musicObj.getId(), true));
                    });
                }
            }
        });
    }

    private void changePlayType() {
        if (mPlayer.getRepeatMode() == Player.REPEAT_MODE_ALL) {
            if (mPlayer.getShuffleModeEnabled()) {
                mPlayer.setShuffleModeEnabled(false);
                binding.ivType.setImageResource(R.drawable.ic_pm_type_1);
            } else {
                mPlayer.setRepeatMode(Player.REPEAT_MODE_ONE);
                binding.ivType.setImageResource(R.drawable.ic_pm_type_2);
            }
        } else if (mPlayer.getRepeatMode() == Player.REPEAT_MODE_ONE) {
            mPlayer.setRepeatMode(Player.REPEAT_MODE_ALL);
            mPlayer.setShuffleModeEnabled(true);
            binding.ivType.setImageResource(R.drawable.ic_pm_type_3);
        }
    }

    boolean shouldPlay = false;

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer.isPlaying()) {
            shouldPlay = true;
            mPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (shouldPlay) {
            shouldPlay = false;
            mPlayer.play();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        long time = mPlayer.getCurrentPosition();
        mPlayer.removeListener(listener);
        stopTimer();
        mPlayer.setRepeatMode(Player.REPEAT_MODE_ALL);
        mPlayer.setShuffleModeEnabled(false);
        if (shouldPlay) {
            PlayManager.getInstance().startPlay(list, current, time);
        }
    }
}
